package http

import (
	"github.com/gin-gonic/gin"
	"strconv"
	"publish/app/ttkb/model"
)


func ListArticle(ctx *gin.Context) Result{
	typ := ctx.Query("type")

	articles,err := model.ListArticle(typ)
	if err != nil {
		return ErrorResult(err)
	}

	return DataResult(articles)
}

func ListArticleByPage(ctx *gin.Context) Result{
	typ := ctx.Query("type")

	pageQ := ctx.DefaultQuery("page","1")
	sizeQ := ctx.DefaultQuery("size","10")
	page,_ := strconv.Atoi(pageQ)
	size,_ := strconv.Atoi(sizeQ)

	result,count,err := model.ListArticleByPage(typ,page,size)
	if err != nil{
		return ErrorResult(err)
	}

	return DataResult(model.Page{Page:page,PageSize:size,Count:count,Data:result})
}

func SearchArticleByPage(ctx *gin.Context) Result{
	word := ctx.Query("word")
	pageQ := ctx.DefaultQuery("page","1")
	sizeQ := ctx.DefaultQuery("size","10")
	page,_ := strconv.Atoi(pageQ)
	size,_ := strconv.Atoi(sizeQ)

	result,count,err := model.SearchArticleByPage(word,page,size)
	if err != nil{
		return ErrorResult(err)
	}

	return DataResult(model.Page{Page:page,PageSize:size,Count:count,Data:result})
}

func UpdateArticle(ctx *gin.Context) Result{

	article := &model.Article{}
	if err := ctx.BindJSON(article);err != nil{
		return BindErrorResult
	}

	err := model.UpdateArticle(article)
	if err != nil{
		return ErrorResult(err)
	}

	return DataResult(article)
}
